package com.kotiln.lgc.rxjava;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //ImageView用于显示图片
    private ImageView mImageView;

    private ProgressDialog mProgressDialog;

    private String imageAddressUrl = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3695073520,824249715&fm=26&gp=0.jpg";

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (mProgressDialog != null) mProgressDialog.dismiss();
            Bitmap bitmap = (Bitmap) message.obj;
            mImageView.setImageBitmap(bitmap);
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = findViewById(R.id.imageView);
        Button btn = (Button) findViewById(R.id.btnchuantong);
        btn.setOnClickListener(this);
        Button btnRX = findViewById(R.id.btnrxjava);
        btnRX.setOnClickListener(this);
    }

    //传统思维
    public void downloadImageAction() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("download run...");
        mProgressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(imageAddressUrl);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(5000);
                    int responseCode = urlConnection.getResponseCode();
                    if (HttpURLConnection.HTTP_OK == responseCode) {
                        Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
                        Message message = handler.obtainMessage();
                        message.obj = bitmap;
                        handler.sendMessage(message);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    @SuppressLint("CheckResult")
    public void rxJavaDownloadImageAction() {
        //起点(Observable) ~~~上游(做耗时操作)~~~订阅~~~下游(更新UI) ~~~终点(Observer)

        //起点  imageAddressUrl为事件源 分发事件
        //第二步
        Observable.just(imageAddressUrl)
                //第三步
                .map(new Function<String, Bitmap>() {
                    @io.reactivex.annotations.NonNull
                    @Override
                    public Bitmap apply(@io.reactivex.annotations.NonNull String s) throws Exception {
//                        URL url=new URL(s);
//                        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//                        conn.setConnectTimeout(5000);
//                         int code = conn.getResponseCode();
//                         if(HttpURLConnection.HTTP_OK == code){
//                             Bitmap bitmap=BitmapFactory.decodeStream(conn.getInputStream());
//                             return bitmap;
//                         }
                        OkHttpClient okHttpClient = new OkHttpClient();
                        Request request = new Request.Builder().url(s).get().build();
                        Call call = okHttpClient.newCall(request);
                        Response response = call.execute();
                        InputStream inputStream = response.body().byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    }
                })

                //如果需要对上面拿到的Bitmap数据进行其它操作 可执行以下代码,依次类推
                //.map(new Function<Bitmap, Bitmap>() {
                //  @io.reactivex.annotations.NonNull
                //  @Override
                // public Bitmap apply(@io.reactivex.annotations.NonNull Bitmap bitmap) throws Exception {
                //     return null;
                // }
                // })

                //给上游分配异步线程
                .subscribeOn(Schedulers.io())

                //给下游分配Android主线程
                .observeOn(AndroidSchedulers.mainThread())

                //订阅  把起点 与 终点 关联起来,此方法以上逻辑为上游 以下逻辑为下游戏
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        //第一步
                        mProgressDialog = new ProgressDialog(MainActivity.this);
                        mProgressDialog.setTitle("RxJava Run...");
                        mProgressDialog.show();

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {//从上游分发下来的事件
                        //第四步 更新UI
                        mImageView.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onError(Throwable e) {//若是执行了onError 便不会再执行onComplete
                        if (mProgressDialog != null) mProgressDialog.dismiss();
                    }

                    @Override
                    public void onComplete() {//代表 链条 结束了; 或是执行了onComplete再执行onError,内部会报错
                        //第五步 终点 全部结束
                        if (mProgressDialog != null) mProgressDialog.dismiss();

                    }
                });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnchuantong:
                downloadImageAction();
                break;
            case R.id.btnrxjava:
                rxJavaDownloadImageAction();
                break;
        }
    }
}